<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <style>
        table {
            border: 1px solid #000;
            text-align: center;
            width: 240px;
        }

        th, td {
            border: 1px solid #000;
        }

        h3 {
            position: relative;
        }

        h3 span {
            position: absolute;
            left: 145px;
            top: -4px;
            width: 16px;
            height: 16px;
            color: white;
            font-size: 12px;
            text-align: center;
            border-radius: 50%;
            background-color: #e63f32;
        }

        input {
            width: 30px;
        }
    </style>
    <script src="../vue.global.js"></script>
</head>
<body>
<div id="app">
    <h3>小黑的礼物清单🛒<span>{{ totalCount }}</span></h3>
    <table>
        <tr>
            <th>名字</th>
            <th>数量</th>
        </tr>
        <tr :key="item.id" v-for="(item, index) in list">
            <td>{{ item.name }}</td>
            <td>{{ item.num }}个</td>
        </tr>
    </table>

    <!-- 目标：统计求和，求得礼物总数 -->
    <p>礼物总数：{{ totalCount }} 个</p>

    姓：<input type="text" v-model="firstName"> +
    名：<input type="text" v-model="lastName"> =
    <span>{{ fullName }}</span><br><br>

    <button @click="changeName">改名卡</button>
</div>

<script>
    const {createApp, ref, computed} = Vue;
    createApp({
        setup() {
            const list = ref([
                {id: 1, name: '篮球', num: 1},
                {id: 2, name: '玩具', num: 2},
                {id: 3, name: '铅笔', num: 6},
            ]);

            const firstName = ref('刘');
            const lastName = ref('备');

            const totalCount = computed(() => {
                return list.value.reduce((sum, item) => sum + item.num, 0);
            });

            const fullName = computed({
                get() {
                    return firstName.value + lastName.value;
                },
                set(value) {
                    firstName.value = value.slice(0, 1);
                    lastName.value = value.slice(1);
                }
            });

            const changeName = () => {
                fullName.value = '吕小布';
            };


            return {list, firstName, lastName, totalCount, fullName, changeName};
        },
    }).mount('#app');
</script>
</body>
</html>
